<?php
namespace app\we\controller;
use think\Controller;
use think\helper\Time;


class Feed extends Controller{


    public function _initialize(){

        $this->rank=array(1=>'好评',2=>'中评',3=>'差评');
        $this->rankico=array(1=>"/:strong",2=>'/:,@f',3=>"/:weak");
      
    }

    public function index($openid=""){
      $fans=model('WeFans')->info($openid);
      $we=model('We')->info($fans['appid']);
      if(request()->isPost()){
        $data=input('post.');
        // 数据有效性
        $content_arr=chararray($data['content']);
        if (!$data['content'] || count($content_arr[0])<=5)$this->error('提示：为了获得更大的卡券，系统建议您写更详细的反馈！');
        $data['aid']=$fans['aid'];
        $data['appid']=$fans['appid'];
        $data['nickname']=$fans['nickname'];
         //处理表情
       
        //计算当日反馈数量
        $today = Time::today();
        $today_total=db('WeFeed')->where('shopid',$data['shopid'])->whereTime('create_time','today')->count();
        $data['today_um']=$data['shopid'].'-'.($today_total+1);
        $today_my_total=db('WeFeed')->where('openid',$data['openid'])->whereTime('create_time','today')->count();
        if ($today_my_total>0) $this->error('您今天已经反馈，谢谢');
        $feed_id=model('we/WeFeed')->editData($data);
        
        if ($feed_id){
        //优先发送客服消息，失败后发送模板消息
            $admins=model('we/WeFans')->getAdmins($fans['appid']);
            $shop=model('admin/AdminShop')->info($data['shopid']);
            $message_first=$shop['title']."第".($today_total+1).'条客情：'.$data['target'];
            $message_keyword1='产品'.$this->rank[$data['product']].'-服务'.$this->rank[$data['service']];
            $message_keyword2=date('Y-m-d H:i:s',time());
            $message_remark=$fans['nickname'].':'.$data['content'];
          

            foreach ($admins as $key => $admin) {
               $url=my_domain().url('chatAdmin',['feed_id'=>$feed_id,'admin_openid'=>$admin['openid']]);
               $reply=[
                'template_id'=>'x8iWBbDQQ05Ey0hAJkIg6pakL1Q8mTCiiFE87pRy7ck',
                'url'=>$url,
                'data'=>[
                'first'=>['value'=>$message_first],
                'keyword1'=>['value'=>$message_keyword1],
                'keyword2'=>['value'=>$message_keyword2],
                'remark'=>['value'=>$message_remark,"color"=>"#fc0b0b"]
                ]
                ];
               
               template_message($admin['openid'],$reply);
            }
            // custom_message($fans['openid'],'您的反馈我们已经收到，谢谢！么么哒');
            if ($we['feed_card']){
               $card_message=['msgtype'=>'wxcard','wxcard'=>['card_id'=>$we['feed_card']]];
               custom_message($fans['openid'],$card_message);
            }

            $this->success('成功反馈',$we['feed_url']);
        }
        $this->error('反馈失败');

      }else{
        $shops=my_select('AdminShop','id','title',['aid'=>$fans['aid']]);
        $scan=model('we/WeSceneScan')->getLastAdmin($openid);
       
        $this->assign('openid',$openid);
        $this->assign('scan',$scan);
        $this->assign('shops',$shops);
        return $this->fetch();
      }
  
       
    }

    public function index2($openid=""){
      $fans=model('WeFans')->info($openid);
      $we=model('We')->info($fans['appid']);
      if(request()->isPost()){
        $data=input('post.');
        // 数据有效性
        $content_arr=chararray($data['content']);
        if (!$data['content'] || count($content_arr[0])<=5)$this->error('提示：为了获得更大的卡券，系统建议您写更详细的反馈！');
        $data['aid']=$fans['aid'];
        $data['appid']=$fans['appid'];
        $data['nickname']=$fans['nickname'];
         //处理表情
       
        //计算当日反馈数量
        $today = Time::today();
        $today_total=db('WeFeed')->where('shopid',$data['shopid'])->whereTime('create_time','today')->count();
        $data['today_um']=$data['shopid'].'-'.($today_total+1);
        $today_my_total=db('WeFeed')->where('openid',$data['openid'])->whereTime('create_time','today')->count();
        if ($today_my_total>0) $this->error('您今天已经反馈，谢谢');
        $feed_id=model('we/WeFeed')->editData($data);
        
        if ($feed_id){
        //优先发送客服消息，失败后发送模板消息
            $admins=model('we/WeFans')->getFeedAdmins($fans['appid']);
            $shop=model('admin/AdminShop')->info($data['shopid']);
            $message_first=$shop['title']."第".($today_total+1).'条客情：'.$data['target'];
            $message_keyword1='产品'.$this->rank[$data['product']].'-服务'.$this->rank[$data['service']];
            $message_keyword2=date('Y-m-d H:i:s',time());
            $message_remark=$fans['nickname'].':'.$data['content'];
          

            foreach ($admins as $key => $admin) {
               $url=my_domain().url('chatAdmin',['feed_id'=>$feed_id,'admin_openid'=>$admin['openid']]);
               $reply=[
                'template_id'=>'x8iWBbDQQ05Ey0hAJkIg6pakL1Q8mTCiiFE87pRy7ck',
                'url'=>$url,
                'data'=>[
                'first'=>['value'=>$message_first],
                'keyword1'=>['value'=>$message_keyword1],
                'keyword2'=>['value'=>$message_keyword2],
                'remark'=>['value'=>$message_remark,"color"=>"#fc0b0b"]
                ]
                ];
               
               template_message($admin['openid'],$reply);
            }

            // custom_message($fans['openid'],'您的反馈我们已经收到，谢谢！么么哒');
            if ($we['feed_card']){
               $card_message=['msgtype'=>'wxcard','wxcard'=>['card_id'=>$we['feed_card']]];
               custom_message($fans['openid'],$card_message);
            }

            //如果要打赏则支付
            if ($data['pay']){
              $pay=[
              'aid'=>$fans['aid'],
              'appid'=>$fans['appid'],
              'openid'=>$fans['openid'],
              'product'=>'打赏服务员',
              'description'=>'感谢您的打赏，我们会再接再厉',
              'price'=>$data['pay'],
              'um'=>1,
              'url'=>'we/WeFeed',
              'data_id'=>$feed_id
              ];
              session('pay',$pay);
              $this->success('成功反馈',url('we/pay/jssdk'));
            }else{
              $this->success('成功反馈',$we['feed_url']); 
            }

        }
        $this->error('反馈失败');

      }else{
        $shops=my_select('AdminShop','id','title',['aid'=>$fans['aid']]);
        $scan=model('we/WeSceneScan')->getLastAdmin($openid);
        $shopid=model('we/WeFans')->SmartShopid($openid);
        $this->assign('myJssdk',['appid'=>$fans['appid']]);
       
        $this->assign('openid',$openid);
        $this->assign('scan',$scan);
        $this->assign('shops',$shops);
        $this->assign('shopid',$shopid);
        return $this->fetch();
      }
  
       
    }

    public function chatAdmin($feed_id="",$admin_openid=''){

      $feed=model('we/WeFeed')->info($feed_id);

      if (!$feed) $this->error('回话已经过期,或者您已经切好分店，请关闭后重新进入管理面板');
      if (!$admin_openid){
        $admin_auth=we_auth($feed['appid']);
        if ($admin_auth) $admin_openid=$admin_auth['openid'];
      }
      $fans=model('we/WeFans')->info($feed['openid']); //获取了使用者
      $admin=model('we/WeFans')->info($admin_openid); //获取了客服
      if (!$admin['admin']) die('未登陆');
     

      if(request()->isPost()){
        $data=input('post.');
        // 数据有效性
        
        $data['aid']=$fans['aid'];
        $data['feed']=$data['feed_id'];
        $data['nickname']=$fans['nickname'];
        $data['admin_openid']=$admin['openid'];
        $data['admin_nickname']=$admin['nickname'];
        $data['type']=1;

        //快速回复
        if(!$data['content'] and $data['quick_content']){
          $data['content']=$data['quick_content'];
          unset($data['quick_content']);
        }
        
       
        if($data['product']!=$feed['product']) {
          $res=db('WeFeed')->where('id',$data['feed_id'])->update(['product'=>$data['product']]);
          $data['content'].= $data['admin_nickname']."修改产品".$this->rank[$feed['product']].'为'.$this->rank[$data['product']];
        }
        if($data['service']!=$feed['service']){
          $res=db('WeFeed')->where('id',$data['feed_id'])->update(['service'=>$data['service']]);
          $data['content'].= "--".$data['admin_nickname']."修改服务".$this->rank[$feed['service']].'为'.$this->rank[$data['service']];
        } 
         
        if (isset($data['card_id'])) {
           if ($data['card_id']) {
                $card=model('we/weCard')->info($data['card_id']);
                $message=['msgtype'=>'wxcard','wxcard'=>['card_id'=>$data['card_id']]];
                $message_error=custom_message($feed['openid'],$message);
                if ( $message_error)$data['content'].='，发送卡券失败'.$message_error;
                $data['content'].='，赠送您一张'.$card['title'].'卡券，请注意查收！么么哒';
            }
        }

                $message_first="留言(".$feed['id']."):".$feed['content'];
                $message_keyword1='产品'.$this->rank[$feed['product']].'-服务'.$this->rank[$feed['service']];
                $message_keyword2=date('Y-m-d H:i:s',time());
                $message_remark=$data['admin_nickname'].':'.$data['content'];
                $url=my_domain().url('chat',['feed_id'=>$feed_id,'openid'=>$fans['openid']]);
                $reply=[
                  'template_id'=>'x8iWBbDQQ05Ey0hAJkIg6pakL1Q8mTCiiFE87pRy7ck',
                  'url'=>$url,
                  'data'=>[
                  'first'=>['value'=>$message_first],
                  'keyword1'=>['value'=>$message_keyword1],
                  'keyword2'=>['value'=>$message_keyword2],
                  'remark'=>['value'=>$message_remark,"color"=>"#fc0b0b"]
                  ]
                ];
                $message_error=template_message($feed['openid'],$reply); 
         


      $data['content'] = ubbReplace($data['content']);
      $chat_id=model('we/WeFeedChat')->editData($data);
      if ($chat_id)$this->success('成功反馈'.$message_error,url('chatAdmin',['feed_id'=>$feed_id,'admin_openid'=>$admin_openid,'time'=>time()]));
        
      $this->error('反馈失败');

      }else{

        //加载扫码和卡券
          $fans_cards=get_fans_card($fans['appid'],$fans['openid']);
            if ($fans_cards){
            $cards_info='</br>该粉丝拥有';
            foreach ($fans_cards['card_list'] as $key => $fans_card) {
               $this_card= db('WeCard')->where('card_id',$fans_card['card_id'])->find();
               $cards_info.="</br>".$this_card['id']."号-".$this_card['title'];
            }
          }

          $cards=db('WeCard')->where('appid',$fans['appid'])->where('status>0')->select();
          
         
          //扫码记录
          $scans=model('WeSceneScan')->where('openid',$fans['openid'])->where('qrcode_type',1)->order('create_time desc')->limit(5)->select();
          $scans_info="</br>扫码记录";
          foreach ($scans as $key => $scan) {
             if($scan['admin'])$admin=model('admin/AdminUser')->info($scan['admin']);
             if($scan['shopid'])$shop=model('admin/AdminShop')->info($scan['shopid']);
             $scans_info.="</br>".date('m-d H:i',$scan['create_time'])."扫描".$shop['title'].$scan['qrcode'].'-'.(isset($admin['name'])?$admin['name']:'');
          }

           //记星记录
          $scores=model('WeFansCfoLog')->where('type=1')->where('openid',$fans['openid'])->order('create_time desc')->limit(5)->select();
          $scores_info="</br>最近积星记录";
          foreach ($scores as $key => $score) {
             $admin=$shop=[];
             if($score['admin'])$admin=model('admin/AdminUser')->info($score['admin']);
             if($score['shopid'])$shop=model('admin/AdminShop')->info($score['shopid']);
             $scores_info.="</br>".date('m-d H:i',$score['create_time'])."在".(isset($shop['title'])?$shop['title']:'').(isset($admin['name'])?$admin['name']:'').'记星'.$score['um'].',结余'.$score['balance'];
          }
      

        //加载对话内容
        $chats=db('WeFeedChat')->where('feed',$feed_id)->select();
          if ($chats){
            foreach ($chats as $key => &$chat) {
                $admin=model('we/WeFans')->info($chat['admin_openid']);
                if ($chat['type']==1){
                  $chat['headimgurl']=$admin['headimgurl'];
                }else{
                  $chat['headimgurl']=$fans['headimgurl'];
                }
            }
        }

        $this->assign('feed',$feed);
        $this->assign('chats',$chats);
        $this->assign('fans',$fans);
        // $this->assign('fans_info',$fans_info);
        $this->assign('cards',$cards);
        $this->assign('admin_openid',$admin_openid);
        $this->assign('ranks',$this->rank);
        $this->assign('myJssdk',['appid'=>$fans['appid']]);
       
        if (isset($cards_info))$this->assign('cards_info',$cards_info);
        if (isset($scans_info))$this->assign('scans_info',$scans_info);
        if (isset($scores_info))$this->assign('scores_info',$scores_info);
      
        return $this->fetch();
      }
  
       
    }


    public function chat($feed_id="",$openid=''){

      $feed=model('WeFeed')->info($feed_id);
      if (!$feed) die('回话已经过期');
      if ($openid and $openid!=$feed['openid']) die('无权回复');
      $fans=model('we/WeFans')->info($feed['openid']); //获取了使用者
      
      //加载对话内容
      $chats=db('WeFeedChat')->where('feed',$feed_id)->select();
          if ($chats){
            foreach ($chats as $key => &$chat) {
                $admin=model('we/WeFans')->info($chat['admin_openid']);
                if ($chat['type']==1){
                  $chat['headimgurl']=$admin['headimgurl'];
                }else{
                  $chat['headimgurl']=$fans['headimgurl'];
                }
            }
      }

      if(request()->isPost()){
        $data=input('post.');
        // 数据有效性
        
        $data['aid']=$fans['aid'];
        $data['feed']=$data['feed_id'];
        $data['nickname']=$fans['nickname'];
        $data['admin_openid']=$admin['openid'];
        $data['admin_nickname']=$admin['nickname'];
        $data['type']=0;
       
       
        $chat_id=model('we/WeFeedChat')->editData($data);
        
        if ($chat_id){
           
            $message_first=$fans['id']."号顾客 - 评价".$feed['target'];
            $message_keyword1=$this->rank[$feed['product']].'-服务'.$this->rank[$feed['service']];
            $message_keyword2=date('Y-m-d H:i:s',time());
            $message_remark=$fans['nickname'].':'.$data['content'];
            $url=my_domain().url('chatAdmin',['feed_id'=>$feed_id,'admin_openid'=>$admin['openid']]);
            $reply=[
              'template_id'=>'x8iWBbDQQ05Ey0hAJkIg6pakL1Q8mTCiiFE87pRy7ck',
              'url'=>$url,
              'data'=>[
              'first'=>['value'=>$message_first],
              'keyword1'=>['value'=>$message_keyword1],
              'keyword2'=>['value'=>$message_keyword2],
              'remark'=>['value'=>$message_remark,"color"=>"#fc0b0b"]
              ]
            ];
           $message_error=template_message($admin['openid'],$reply);
           $this->success('成功反馈'.$message_error,url('chat',['feed_id'=>$feed_id,'openid'=>$openid,'time'=>time()]));
        }
        $this->error('反馈失败');

      }else{
      
        $this->assign('feed',$feed);
        $this->assign('chats',$chats);
        $this->assign('fans',$fans);
       
       
        return $this->fetch();
      }
  
       
    }




   
}